package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务类
 */

@Component
@Slf4j
public class MyTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理超时订单
     */
    @Scheduled(cron = "0 * * * * ? ")//每分钟触发一次
    private void processTimeOutOrder(){
        log.info("开始定时处理超时订单，时间：{}", LocalDateTime.now());

        //获取超时的订单,
        //订单状态为支付中，订单时间超过15分钟了
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> outTimeOrders= orderMapper.getOutTimeOrders(Orders.PENDING_PAYMENT,time);

        //如果有，修改 这些订单的状态等信息
        if (outTimeOrders!=null && outTimeOrders.size()>0){
            for (Orders order : outTimeOrders) {
                order.setStatus(Orders.CANCELLED);
                order.setCancelTime(LocalDateTime.now());
                order.setCancelReason("订单超时，自动取消。");
                orderMapper.update(order);
            }
        }
    }

    /**
     * 处理派送中的订单
     */
    @Scheduled(cron = "0 0 1 * * ? ")//每天凌晨1点执行
    private void processDeliveryOrder(){
        log.info("开始定时处理派送中的订单，时间：{}", LocalDateTime.now());

        //获取派送中的订单，只要获取状态是派送中的就行
        List<Orders> deliveringOrders=orderMapper.getDeliveryOrder(Orders.DELIVERY_IN_PROGRESS);
        //有就修改状态为 已完成 状态
        if (deliveringOrders!=null && deliveringOrders.size()>0){
            for (Orders order : deliveringOrders) {
                order.setStatus(Orders.COMPLETED);
                orderMapper.update(order);
            }
        }

    }
}
